//
//  ASHomeViewController.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/27.
//

#import "ASHomeViewController.h"
#import "ASHomeHeadView.h"
#import "ASHomeBannerModel.h"
#import "ASHomeApi.h"
#import "MJRefreshNormalHeader.h"
#import "MJRefreshAutoNormalFooter.h"
#import "ASHomeHeadFeaturedView.h"
#import "ASHomeMainCell.h"
#import "ASHomeModel.h"
#import "ASNoneView.h"
#import "ASHomeSearchController.h"
#import "ASDetailController.h"
#import "ASClassGroupVC.h"
#import "ASServiceModel.h"

@interface ASHomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) NSArray *bannerArr;
@property (strong, nonatomic) NSMutableArray *listArr;
@property (strong, nonatomic) ASHomeMainModel *featuredObj;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) ASNoneView *noneView;
@property (strong, nonatomic) UIButton *goTopBtn;

@end

@implementation ASHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"头像秀秀";
    self.view.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.goTopBtn];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    [self loadAllOtherData];
    [self loadHomeBannerData];
    [self firstLoadData:YES];
    [self crateSearchBtn];
    // Do any additional setup after loading the view.
}

- (void)crateSearchBtn{
    UIButton *searchBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [searchBtn setImage:[UIImage imageNamed:@"home_ss"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(clickSearchBtn) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchBtn];
}

- (void)clickSearchBtn{
    [ASTool addUMTongJiKey:@"home" subKey:@"home_top" titleStr:@"搜索"];
    ASHomeSearchController *searchVC = [ASHomeSearchController new];
    searchVC.hidesBottomBarWhenPushed = YES;
    [currViewController().navigationController pushViewController:searchVC animated:YES];
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *fl = [UICollectionViewFlowLayout new];
        fl.minimumLineSpacing = 7;
        fl.minimumInteritemSpacing = 7;
        fl.sectionInset = UIEdgeInsetsMake(0, 13, 13, 13);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:fl];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = self.view.backgroundColor;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[ASHomeHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ASHomeHeadViewStr];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionReusableViewFoot"];

        [_collectionView registerClass:[ASHomeHeadFeaturedView class] forCellWithReuseIdentifier:ASHomeHeadFeaturedViewStr];
        [_collectionView registerClass:[ASHomeMainCell class] forCellWithReuseIdentifier:ASHomeMainCellStr];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCellNone"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadAllData)];
        header.lastUpdatedTimeLabel.hidden = YES;
        _collectionView.mj_header = header;
        
        MJRefreshAutoNormalFooter *foot = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [foot endRefreshingWithNoMoreData];
        [foot setTitle:@"" forState:MJRefreshStateNoMoreData];
        _collectionView.mj_footer = foot;
    }
    return _collectionView;
}

- (ASNoneView *)noneView{
    if (!_noneView) {
        _noneView = [[ASNoneView alloc]initWithFrame:CGRectZero];
        [_noneView.logoImage setImage:[UIImage imageNamed:@"me_wsj"]];
        _noneView.titleLab.text = @"暂时没有相关数据";
    }
    return _noneView;
}

- (UIButton *)goTopBtn{
    if (!_goTopBtn) {
        _goTopBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 40 - 14, SCREENH_HEIGHT - Height_TabBar - 6 -40, 40, 40)];
        [_goTopBtn setImage:[UIImage imageNamed:@"home_xfc"] forState:UIControlStateNormal];
        [_goTopBtn addTarget:self action:@selector(clickTopBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _goTopBtn;
}

- (void)clickTopBtn{
    [self.collectionView setContentOffset:CGPointMake(0, -Height_NavBar) animated:YES];
}

#pragma mark - LoadData
- (void)loadHomeBannerData{
    [ASHomeApi loadHomeBannerCompletion:^(ASHomeBannerModel *  _Nonnull result) {
        if (result.state.intValue == 1) {
            self.bannerArr = result.banner;
            [self.collectionView reloadData];
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
    } failure:^(NSError * _Nonnull error) {
            
    }];
}

- (void)reloadAllData{
    [self loadHomeBannerData];
    [self firstLoadData:YES];
}
///加载全局公共数据
- (void)loadAllOtherData{
    [ASHomeApi loadOpinionDataCompletion:^(ASServiceModel *  _Nonnull result) {
        if (result.state.intValue == 1) {
            ASServiceModel *model = [ASServiceModel sharedManger];
            model.lx_qq = result.lx_qq;
            model.qq_group = result.qq_group;
            model.qq_key = result.qq_key;
            model.access_token = result.access_token;
            model.access_anime_token = result.access_anime_token;
            model.close_mobile_login = result.close_mobile_login;
            model.usage_count = result.usage_count;
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}
- (void)firstLoadData:(BOOL)ifHUD{
    self.page = 1;
    [self loadMainData:ifHUD];
}

- (void)loadMoreData{
    self.page ++;
    [self loadMainData:NO];
}

- (void)loadMainData:(BOOL)ifHUD{
    if (ifHUD) {
        [MBProgressHUD showMessage:@"加载中..."];
    }
    [ASHomeApi loadHomeHomeListPage:self.page Completion:^(ASHomeModel *  _Nonnull result) {
        [MBProgressHUD hideHUD];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (result.state.intValue == 1) {
            if (self.page == 1) {
                [self.listArr removeAllObjects];
                self.listArr = [NSMutableArray new];
                self.featuredObj = result.featured;
            }
            
            ///过滤重复数据
            for (ASHomeMainModel *subModel2 in result.list) {
                BOOL hasSave = YES;
                 for (ASHomeMainModel *subModel in self.listArr) {
                     if ([subModel2.tID isEqualToString:subModel.tID] && [subModel2.thumb isEqualToString:subModel.thumb]) {
                         hasSave = NO;
                         break;
                     }
                 }
                if (hasSave == YES) {
                    [self.listArr addObject:subModel2];
                }
            }
            [self.collectionView reloadData];
        }else{
            [MBProgressHUD showError:result.errorMsg];
        }
    } failure:^(NSError * _Nonnull error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:FENETERROR];
    }];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return self.listArr.count>0?self.listArr.count:1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.listArr.count > 0) {
        if (indexPath.section == 0) {
            return CGSizeMake(SCREEN_WIDTH, 160);
        }
        return CGSizeMake((SCREEN_WIDTH - 33)/2, (SCREEN_WIDTH - 33)/2);
    }
    return CGSizeMake(SCREEN_WIDTH, SCREENH_HEIGHT);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH, 190);
    }
    return CGSizeZero;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader] && indexPath.section == 0) {
        ASHomeHeadView *headV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ASHomeHeadViewStr forIndexPath:indexPath];
        headV.dataArr = self.bannerArr;
        return headV;
    }
    UICollectionReusableView *footV = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionReusableViewFoot" forIndexPath:indexPath];
    return footV;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.listArr.count > 0) {
        if (indexPath.section == 0) {
            return [self headCellCollectionView:collectionView cellForItemAtIndexPath:indexPath];
        }
        return [self mainCellCollectionView:collectionView cellForItemAtIndexPath:indexPath];
    }
    return [self noneCellCollectionView:collectionView cellForItemAtIndexPath:indexPath];
}

- (UICollectionViewCell *)headCellCollectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ASHomeHeadFeaturedView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ASHomeHeadFeaturedViewStr forIndexPath:indexPath];
    cell.model = self.featuredObj;
    self.goTopBtn.hidden = YES;
    return cell;
}

- (UICollectionViewCell *)noneCellCollectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCellNone" forIndexPath:indexPath];
    for (UIView *subV in cell.contentView.subviews) {
        if ([subV isKindOfClass:[ASNoneView class]]) {
            [subV removeFromSuperview];
        }
    }
    [cell.contentView addSubview:self.noneView];
    [self.noneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.goTopBtn.hidden = YES;
    return cell;
}

- (UICollectionViewCell *)mainCellCollectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ASHomeMainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ASHomeMainCellStr forIndexPath:indexPath];
    if (self.listArr.count > indexPath.row) {
        cell.model = self.listArr[indexPath.row];
    }
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    FELog(@"scrollView.contentOffset.yscrollView.contentOffset.y=====%.2f===%.2f",scrollView.contentOffset.y,((SCREEN_WIDTH - 33)/2)*10);
    if (scrollView.contentOffset.y > ((((SCREEN_WIDTH - 33)/2)*10 - 190)) ) {
        self.goTopBtn.hidden = NO;
    }else{
        self.goTopBtn.hidden = YES;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        [ASTool addUMTongJiKey:@"home" subKey:@"home_top" titleStr:@"精选套图_图集"];
        ASClassGroupVC *groupVC = [ASClassGroupVC new];
        groupVC.subID = self.featuredObj.tID;
        groupVC.hidesBottomBarWhenPushed = YES;
        groupVC.title = @"精选套图";
        [self.navigationController pushViewController:groupVC animated:YES];
    }else if (self.listArr.count > 0 && indexPath.section > 0) {
        [ASTool addUMTongJiKey:@"home" subKey:@"home_top" titleStr:@"每日精选"];
        ASDetailController *detailVC = [ASDetailController new];
        detailVC.hidesBottomBarWhenPushed = YES;
        [detailVC createOldArr:self.listArr showIndex:indexPath.row];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
